package com.salesmanager.core.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.net.URLEncoder;
import java.nio.charset.CodingErrorAction;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.config.MessageConstraints;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class HttpClientUtil {
	private static Logger LOGGER = LoggerFactory.getLogger(HttpClientUtil.class);
     
    private static PoolingHttpClientConnectionManager connManager = null;
    private static CloseableHttpClient httpclient = null;
    private static ObjectMapper mapper = null;
    static {
        try {
        	mapper = new ObjectMapper();
        	
            SSLContext sslContext = SSLContexts.custom().useTLS().build();
            sslContext.init(null,
                    new TrustManager[] { new X509TrustManager() {
                         
                        public X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }
 
                        public void checkClientTrusted(
                                X509Certificate[] certs, String authType) {
                        }
 
                        public void checkServerTrusted(
                                X509Certificate[] certs, String authType) {
                        }
                    }}, null);
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.INSTANCE)
                    .register("https", new SSLConnectionSocketFactory(sslContext))
                    .build();
             
            connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            httpclient = HttpClients.custom().setConnectionManager(connManager).build();
            // Create socket configuration
            SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
            connManager.setDefaultSocketConfig(socketConfig);
            // Create message constraints
            MessageConstraints messageConstraints = MessageConstraints.custom()
                .setMaxHeaderCount(200)
                .setMaxLineLength(2000)
                .build();
            // Create connection configuration
            ConnectionConfig connectionConfig = ConnectionConfig.custom()
                .setMalformedInputAction(CodingErrorAction.IGNORE)
                .setUnmappableInputAction(CodingErrorAction.IGNORE)
                .setCharset(Consts.UTF_8)
                .setMessageConstraints(messageConstraints)
                .build();
            connManager.setDefaultConnectionConfig(connectionConfig);
            connManager.setMaxTotal(200);
            connManager.setDefaultMaxPerRoute(20);
        } catch (KeyManagementException e) {
        	LOGGER.error("KeyManagementException", e);
        } catch (NoSuchAlgorithmException e) {
        	LOGGER.error("NoSuchAlgorithmException", e);
        }
    }
    public static String post(String url, int timeout, String data, String encoding){
        HttpPost post = new HttpPost(url);
        try {
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(timeout)
                    .setConnectTimeout(timeout)
                    .setConnectionRequestTimeout(timeout)
                    .setExpectContinueEnabled(false).build();
            post.setConfig(requestConfig);
             
            StringEntity myEntity = new StringEntity(data, "UTF-8"); 
            post.setHeader("Content-type", "text/xml");
            post.setEntity(myEntity); 
            
            LOGGER.info("[HttpUtils Post] begin invoke url:" + url + " , data:"+data);
            CloseableHttpResponse response = httpclient.execute(post);
            try {
                HttpEntity entity = response.getEntity();
                try {
                    if(entity != null){
                        String postRetValue = EntityUtils.toString(entity, encoding);
                        LOGGER.info("[HttpUtils Post]Debug response, url :" + url + " , response string :"+postRetValue);
                        return postRetValue;
                    }
                } finally {
                    if(entity != null){
                        entity.getContent().close();
                    }
                }
            } finally {
                if(response != null){
                    response.close();
                }
            }
        } catch (UnsupportedEncodingException e) {
        	LOGGER.error("UnsupportedEncodingException", e);
        } catch (Exception e) {
        	LOGGER.error("Exception", e);
        } finally {
            post.releaseConnection();
        }
        return null;
    }     
//    public static String postJsonBody(String url, int timeout, Map<String, Object> map, String encoding){
//        HttpPost post = new HttpPost(url);
//        try {
//            post.setHeader("Content-type", "application/json");
//            RequestConfig requestConfig = RequestConfig.custom()
//                    .setSocketTimeout(timeout)
//                    .setConnectTimeout(timeout)
//                    .setConnectionRequestTimeout(timeout)
//                    .setExpectContinueEnabled(false).build();
//            post.setConfig(requestConfig);
//             
//            String postStr = mapper.writeValueAsString(map);
//            LOGGER.info("[HttpUtils Post] begin invoke url:" + url + " , params:"+postStr);
//            CloseableHttpResponse response = httpclient.execute(post);
//            try {
//                HttpEntity entity = response.getEntity();
//                try {
//                    if(entity != null){
//                        String postRetValue = EntityUtils.toString(entity, encoding);
//                        LOGGER.info("[HttpUtils Post]Debug response, url :" + url + " , response string :"+postRetValue);
//                        return postRetValue;
//                    }
//                } finally {
//                    if(entity != null){
//                        entity.getContent().close();
//                    }
//                }
//            } finally {
//                if(response != null){
//                    response.close();
//                }
//            }
//        } catch (UnsupportedEncodingException e) {
//        	LOGGER.error("UnsupportedEncodingException", e);
//        } catch (Exception e) {
//        	LOGGER.error("Exception", e);
//        } finally {
//            post.releaseConnection();
//        }
//        return null;
//    }

    @SuppressWarnings("deprecation")
    public static String invokeGet(String url, Map<String, String> params, String encode, int connectTimeout) {
        String responseString = null;
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(connectTimeout)
                .setConnectTimeout(connectTimeout)
                .setConnectionRequestTimeout(connectTimeout).build();
         
        StringBuilder sb = new StringBuilder();
        sb.append(url);
        int i = 0;
        for (Entry<String, String> entry : params.entrySet()) {
            if (i == 0 && !url.contains("?")) {
                sb.append("?");
            } else {
                sb.append("&");
            }
            sb.append(entry.getKey());
            sb.append("=");
            String value = entry.getValue();
            try {
                sb.append(URLEncoder.encode(value, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
            	LOGGER.warn("encode http get params error, value is "+value, e);
                sb.append(URLEncoder.encode(value));
            }
            i++;
        }
        
        LOGGER.info("[HttpUtils Get] begin invoke:" + sb.toString());
        HttpGet get = new HttpGet(sb.toString());
        get.setConfig(requestConfig);
         
        try {
            CloseableHttpResponse response = httpclient.execute(get);
            try {
                HttpEntity entity = response.getEntity();
                try {
                    if(entity != null){
                        responseString = EntityUtils.toString(entity, encode);
                    }
                } finally {
                    if(entity != null){
                        entity.getContent().close();
                    }
                }
            } catch (Exception e) {
            	LOGGER.error(String.format("[HttpUtils Get]get response error, url:%s", sb.toString()), e);
                return responseString;
            } finally {
                if(response != null){
                    response.close();
                }
            }
            LOGGER.info(String.format("[HttpUtils Get]Debug url:%s , response string %s:", sb.toString(), responseString));
        } catch (SocketTimeoutException e) {
        	LOGGER.error(String.format("[HttpUtils Get]invoke get timout error, url:%s", sb.toString()), e);
            return responseString;
        } catch (Exception e) {
        	LOGGER.error(String.format("[HttpUtils Get]invoke get error, url:%s", sb.toString()), e);
        } finally {
            get.releaseConnection();
        }
        return responseString;
    }
     
    public final static int connectTimeout = 5000;
    /**
     * HTTPS请求，默认超时为5S
     * @param reqURL
     * @param params
     * @return
     */
    public static String connectPostHttps(String reqURL, Map<String, String> params) {
 
        String responseContent = null;
         
        HttpPost httpPost = new HttpPost(reqURL); 
        try {
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(connectTimeout)
                    .setConnectTimeout(connectTimeout)
                    .setConnectionRequestTimeout(connectTimeout).build();
             
            List<NameValuePair> formParams = new ArrayList<NameValuePair>(); 
            httpPost.setEntity(new UrlEncodedFormEntity(formParams, Consts.UTF_8));
            httpPost.setConfig(requestConfig);
            // 绑定到请求 Entry
            for (Map.Entry<String, String> entry : params.entrySet()) {
                formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            CloseableHttpResponse response = httpclient.execute(httpPost);
             try {
                // 执行POST请求
                HttpEntity entity = response.getEntity(); // 获取响应实体
                try {
                    if (null != entity) {
                        responseContent = EntityUtils.toString(entity, Consts.UTF_8);
                    }
                } finally {
                    if(entity != null){
                        entity.getContent().close();
                    }
                }
            } finally {
                if(response != null){
                    response.close();
                }
            }
             LOGGER.info("requestURI : "+httpPost.getURI()+", responseContent: " + responseContent);
        } catch (ClientProtocolException e) {
        	LOGGER.error("ClientProtocolException", e);
        } catch (IOException e) {
        	LOGGER.error("IOException", e);
        } finally {
            httpPost.releaseConnection();
        }
        return responseContent;
    }
    
    public static String doGetToken(String source, String key){
    	try {
			Map<String,Object> userData = mapper.readValue(source, Map.class);
			return (String) userData.get(key);
		} catch (Exception e) {
			LOGGER.error("Http Client Json解析异常");
		} 
    	return null;
    }
    public static void main(String[] args) {
    	String url = "https://api.weixin.qq.com/cgi-bin/token";
    	String APPID = "wx3e1d294235ac349a";
    	String APPSECRET = "038894f3daa38990b60a5d7df63c1e19";
    	
    	Map<String, String> params = new HashMap<String, String>();
    	params.put("grant_type", "client_credential");
    	params.put("appid", APPID);
    	params.put("secret", APPSECRET);
    	//{"access_token":"8_EQa9LRpugkQJq7YRehe1rO3_AdPDaIMhyFbMuuwoKU0vD8ztTMxBIEMCFiafgjlRBRyODcFhxBXsN5Hqx3lTxICze37PDi8aqHgMNGvH8","expires_in":7200}
    	
    	
    	
    	String api_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
    	Map<String, String> params1 = new HashMap<String, String>();
    	params1.put("access_token", "qwm6Kb9MdUZWPk_YvWClg5ui3cj4pPiYgcpyGBXFqFdV7jssuwqAzTWePBHoTokfpjU-toQFpoc_w6kjS_xAwpeu4sirwAHal2ihSuhrEaU");
    	params1.put("type", "wx_card");
    	//{"errcode":0,"errmsg":"ok","ticket":"m7RQzjA_ljjEkt-JCoklRGSWIBQTK1CPBo6moZCCvUtvaujwzkWuOOLY79LVAlDvvRlwbcnm8Qp6536x8TIu7w","expires_in":7200}
//    	String doGetAccessToken = doGetToken(HttpClientUtil.invokeGet(url, params, Consts.UTF_8.toString(), connectTimeout), "access_token");
    	String doGetAccessToken = HttpClientUtil.invokeGet(api_ticket_url, params1, Consts.UTF_8.toString(), connectTimeout);
    	System.out.println(doGetAccessToken);
	}
 
}
